﻿using System;
using SKIT.FlurlHttpClient.Wechat.Api;
using SKIT.FlurlHttpClient.Wechat.Api.Models;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Volo.Abp.Application.Services;

namespace Colorful.Furniture.MpManagement;

/// <summary>
///  微信公众号模板消息服务
/// </summary>
public class WechatMpTemplateAppService : ApplicationService
{
    private readonly IWechatMpExtensions _wechatMpExtensions;
    private readonly WechatApiClient _wechatMpClient;
    private readonly ILogger<WechatMpTemplateAppService> _logger;

    public WechatMpTemplateAppService(IWechatMpExtensions wechatMpExtensions,
        WechatApiClient wechatMpClient,
        ILogger<WechatMpTemplateAppService> logger)
    {
        _wechatMpExtensions = wechatMpExtensions;
        _wechatMpClient = wechatMpClient;
        _logger = logger;
    }

    /// <summary>
    ///  发送消息
    /// </summary>
    /// <param name="input">请求体</param>
    /// <returns></returns>
    public async Task<bool> SendAsync(SendMpTemplateInputDto input)
    {
        try
        {
            var sendTemplateItemData = input.TemplateItemData
                .ToDictionary(
                    templateItemDataInputDto =>
                        templateItemDataInputDto.Name, templateItemDataInputDto =>
                        new CgibinMessageTemplateSendRequest.Types.DataItem { Color = templateItemDataInputDto.Color, Value = templateItemDataInputDto.Value });

            var templateResult = await _wechatMpClient.ExecuteCgibinMessageTemplateSendAsync(
                new CgibinMessageTemplateSendRequest
                {
                    AccessToken = await _wechatMpExtensions.GetAccessTokenAsync(),
                    Url = input.Url,
                    TemplateId = input.TemplateId,
                    ToUserOpenId = input.OpenId,
                    Data = sendTemplateItemData
                });

            _wechatMpExtensions.HandleWxJsonResult(templateResult);

            return true;
        }
        catch (Exception e)
        {
            _logger.LogError($"推送微信公众号模板消息[{input.TemplateId}]失败：{e}");

            return false;
        }

    }

    /// <summary>
    ///  获取所有的模版消息列表
    /// </summary>
    /// <returns></returns>
    public async Task<List<TemplateOutputDto>> GetAllListAsync()
    {
        //获取所有的模版列表
        var privateTemplateResult = await _wechatMpClient.ExecuteCgibinTemplateGetAllPrivateTemplateAsync(new CgibinTemplateGetAllPrivateTemplateRequest
        {
            AccessToken = await _wechatMpExtensions.GetAccessTokenAsync()
        });

        //处理错误信息
        _wechatMpExtensions.HandleWxJsonResult(privateTemplateResult);

        var templateList = privateTemplateResult.TemplateList;

        var templateOutputDtoList = new List<TemplateOutputDto>();

        //排除订阅消息
        foreach (var templateTemplate in templateList.Where(x => x.Title != "订阅模板消息"))
        {
            //获取模版类型集合
            var templateContentList = Regex
                .Split(templateTemplate.Content, @"\n+", RegexOptions.Multiline)
                .ToList();

            var templateOutputDto = new TemplateOutputDto
            {
                TemplateId = templateTemplate.TemplateId,
                TemplateName = templateTemplate.Title,
                TemplateExample = templateTemplate.Example,
                TemplateContent = templateTemplate.Content
            };

            //遍历处理模版项内容
            var index = 1;
            foreach (var templateContent in templateContentList)
            {
                var contentList = templateContent.Split("：")
                    .Select(x =>
                    {
                        var match = Regex.Match(x, @"[^{{]*(?=\.)");

                        return match.Success
                            ? match.Value
                            : x;
                    }).ToList();

                //处理特殊标题
                var title = contentList[0];
                var name = contentList.Count == 1 ? contentList[0] : contentList[1];

                if (index == 1)
                    title = "标题";
                else if (index == templateContentList.Count)
                    title = "备注";

                templateOutputDto.TemplateItemData.Add(new TemplateItemDataOutputDto(name, title));

                index++;
            }

            templateOutputDtoList.Add(templateOutputDto);
        }

        return templateOutputDtoList;
    }

    /// <summary>
    ///  推送系统异常消息给开发人员
    /// </summary>
    /// <returns></returns>
    public async Task SendErrorMessageAsync(string title, string errorMsg, string openId,string date, string templateId= "i5NgT8eGpUPKyOMAkkioLj_SiRCEtAYlI_KMSUXkDA8", string remark = "请及时进行修复和关注。")
    {
        await SendAsync(new SendMpTemplateInputDto
        {
            OpenId = openId,
            TemplateId = templateId,
            TemplateItemData = new List<TemplateItemDataInputDto>
                {
                    new("first",title,"#980000"),
                    new("keyword1",date),
                    new ("keyword2",errorMsg,"#980000"),
                    new("keyword3",""),
                    new("remark",remark)
                }
        });
    }
}